/*
* 存储说明
* 使用云函数存储 只能使用云函数方法删除 不然会越权
* 使用云函数是为了使用小程序图片鉴别api
* */
import Wx from "../utils/Wx";
import CustomError from "../utils/CustomError";
/*
* 小程序端上传文件方法
* openVerify 是否开启验证
* */
async function uploadFile (data = {}, openVerify = true) {
    try {
        const tempFilePath = await Wx.compressImage(data.filePath);
        const uploadFileId = await Wx.uploadFile(data.savePath, tempFilePath);
        openVerify ? await imgSecCheck(uploadFileId) : null;
        return uploadFileId
    } catch (e) {
        throw new CustomError(e, "File.uploadFile").parse()
    }
}

//验证图片合法性
async function imgSecCheck (fileID) {
    try {
        return await Wx.cloudFunction("file", {
            actionName: "imgSecCheck",
            cloudId: fileID
        })
    } catch (e) {
        throw new CustomError(e, "File.imgSecCheck")
    }
}

/*
* 小程序端删除方法
* */
async function deleteFile (list = []) {
    return new Promise(function (resolve, reject) {
        wx.cloud.deleteFile({
            fileList: list,
            success: res => {
                resolve();
            },
            fail: err => {
                reject(new CustomError(err, "File.deleteFile")).parse()
            }
        })

    })
}

/*
* 云函数上传文件方法
* 云函数上传数据不能大于10kb ios云函数会报错
* */
async function cloudUploadFile (data = {}) {
    try {
        let filePath = await Wx.compressImage(data.filePath);
        const tempFilePath = wx.getFileSystemManager().readFileSync(filePath, "base64");
        return await Wx.cloudFunction("file", {
            actionName: "uploadFile",
            file: tempFilePath,
            path: data.savePath
        })
    } catch (e) {
        throw new CustomError(e, "File.cloudUploadFile").parse()
    }
}

/*
* 云函数删除方法
* */
async function cloudDeleteFile (list = []) {
    try {
        return await Wx.cloudFunction("file", {
            actionName: "deleteFile",
            list: list
        })
    } catch (e) {
        throw new CustomError(e, "File.cloudDeleteFile").parse()
    }
}

/*
* 下载图片
* */
async function downloadFile(fileID) {
    return new Promise(function (resolve, reject) {
        wx.cloud.downloadFile({
            fileID: fileID,
            success: res => {
                resolve(res.tempFilePath)
            },
            fail: err => {
                reject(new CustomError(err, "File.cloudDeleteFile"))
            }
        })
    })
}

/*
* 获取文件链接
* */
async function getTempFileURL (list = []) {
    return new Promise(function (resolve, reject) {
        wx.cloud.getTempFileURL({
            fileList: list,
            success: res => {
                resolve(res.fileList)
            },
            fail: err => {
                reject(new CustomError(err, "File.cloudDeleteFile"))
            }
        })

    })
}

module.exports = {
    uploadFile,
    deleteFile,
    cloudUploadFile,
    cloudDeleteFile,
    imgSecCheck,
    downloadFile,
    getTempFileURL
}